<?php
/**
 * 用户体验资格
 */

namespace app\Official\controller;


use app\official\model\Region;
use app\common\controller\Official;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use Login\WangYiSms3;
use think\Exception;
use think\facade\Request;
use app\official\model\UserExperience as UserExperienceModel;

class UserExperience extends Official {

    public function post() {
        try {
            if (Request::isPost()) {
                $params = $this->checkParams('phone,sms_code,city_code');
                if ($params === false) return $this->resErr();
                $res = WangYiSms3::verifySms($params['phone'], $params['sms_code'], RedisKey::USEREXPERIENCECODE);
                if ($res) {
                    UserExperienceModel::post($params);
                    return $this->resData('提交成功', []);
                }
            } else {
                $params = $this->checkParams('');
                if ($params === false) return $this->resErr();
                $rank1 = Region::getDatas([['rank', '=', 1]], 'name,id,city_code');//省
                return $this->resData('success', compact('rank1'));
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 发送手机验证码
     * @return false|string
     */
    public function getSmsCode() {
        try {
            $params = $this->checkParams('phone');
            if ($params === false) return $this->resErr();
            if (empty($params['phone'])) throw new Exception('请输入手机号', RespCode::PARAMS_ERR);
            if (!preg_match('/^1[3-9]\d{9}$/', $params['phone']))
                throw new Exception('请输入正确的手机号', RespCode::PARAMS_ERR);
            $re = WangYiSms3::sendAuthCode(trim($params['phone']), rand(1111, 9999), 5, RedisKey::USEREXPERIENCELOCK, RedisKey::USEREXPERIENCECODE);
            if ($re) return $this->resData('发送成功', []);
            else throw new Exception('发送失败', RespCode::PARAMS_ERR);
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

}